package cn.edu.lit.jsjxy.CourseExample.chapter5;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import cn.edu.lit.jsjxy.CourseExample.R;

public class AudioSrv extends Service
{
    String TAG = getClass().getSimpleName();

    MediaPlayer play;
    Timer timer;
    TimerTask timerTask;

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    public void onCreate()
    {
        Log.d(TAG,"onCreate");
        super.onCreate();

        play = MediaPlayer.create(this, R.raw.lanjingling);
        Toast.makeText(this, "创建后台服务...", Toast.LENGTH_LONG).show();

        timer = new Timer();
        timerTask = new TimerTask()
        {
            @Override
            public void run()
            {
                Random rnd  = new Random();
                int k = rnd.nextInt(1000);

                Log.d(TAG, k+ "  Thread Id: " + Thread.currentThread().getId() );
            }
        };
    }

    public int onStartCommand(Intent intent, int flags, int startId)
    {
        super.onStartCommand(intent, flags, startId);
        Log.d(TAG,"onStartCommand");
        //play.start();


        Toast.makeText(this, "启动后台服务程序，播放音乐...", Toast.LENGTH_LONG).show();

        timer.schedule(timerTask, 1000,5000);

        return START_STICKY;
    }

    public void onDestroy()
    {
        Log.d(TAG,"onDestroy");
        //play.release();
        timer.cancel();
        super.onDestroy();
        Toast.makeText(this, "销毁后台服务！", Toast.LENGTH_LONG).show();
    }
}
